package com.cwj.io.nio.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author: Chenwujie
 * @date: 2021-05-20 16:10
 */
public class EchoServer {
    private final int PORT;

    public EchoServer(int port) {
        PORT = port;
    }

    public static void main(String[] args) throws InterruptedException {
        EchoServer echoServer = new EchoServer(6666);
        echoServer.start();
    }
    public void start() throws InterruptedException {
        final ServerHandler serverHandler = new ServerHandler();
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootStrap = new ServerBootstrap();
        serverBootStrap.group(nioEventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(PORT))
            .childHandler(new ChannelInitializer<SocketChannel>(){

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(serverHandler);
                }
            });
        ChannelFuture sync = null;
        try {
            sync = serverBootStrap.bind().sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            nioEventLoopGroup.shutdownGracefully().sync();
        }

    }
}
